package com.dzsw.javabase.regx.sqllike;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LikeClauseExtractor {

    // 核心匹配规则：
// 1. 列名支持反引号包裹或普通格式：`[^`]+` 或 [\w.]+‌:ml-citation{ref="2,3" data="citationList"}
// 2. 排除包含ESCAPE的情况：负向先行断言 (?!\\s+ESCAPE)‌:ml-citation{ref="1" data="citationList"}
// 3. 匹配问号占位符、字符串、动态参数：\\?|'[^']*'|\"[^\"]*\"|#\\{[^}]*\\}‌:ml-citation{ref="4,5" data="citationList"}
    private static final String REGEX =
            "(?i)(`[^`]+`|[\\w.]+)\\s+LIKE\\s+(\\?|'[^']*'|\"[^\"]*\"|#\\{[^}]*\\})(?!\\s+ESCAPE)";


    public static List<LikeCondition> extractLikeClauses(String sql) {
        List<LikeCondition> clauses = new ArrayList<>();
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
//            Map<String, String> clause = new HashMap<>();
//
//            clause.put("column", matcher.group(1).trim());  // 带反引号的列名或普通列名‌:ml-citation{ref="1" data="citationList"}
//            clause.put("pattern", matcher.group(2).trim()); // LIKE后的参数或字符串‌:ml-citation{ref="3,4" data="citationList"}
            clauses.add(new LikeCondition(
                    matcher.group(0).trim(),
                    matcher.group(1).trim(),
                    matcher.group(2).trim(),
                    null
            ));
        }
        return clauses;
    }

    public static void main(String[] args) {
        String testSQL = "SELECT `user`.`name` FROM users "
                + "WHERE `user`.`name` LIKE ? ESCAPE '\\\\' "  // 带ESCAPE的被排除
                + "AND age LIKE ? "                       // 普通LIKE条件
                + "AND `email` LIKE #{emailParam}";            // 动态参数格式

        List<LikeCondition> results = extractLikeClauses(testSQL);
        results.forEach(clause ->
                System.out.println(clause.getCondition())
        );
    }
}
